<template>
  <div
    v-if="!loading"
    v-loading="loading"
    class="add-content"
  >
    <div class="detail-container">
      <div v-show="form_setting">
        <h3>{{ LANG.CONTENT_SETTINGS }}</h3>
        <fks-form>
          <template v-for="item in templateDetail">
            <div :key="item.fieldName">
              <fks-form-item
                v-if="
                  item.fieldType != 'radio' &&
                    showInAttribute(item.fieldName, item.fieldType)
                "
                :span="24"
                :prop="item.fieldName"
                :label="item.alias"
              >
                <template v-if="item.fieldType == 'text'">
                  <fks-input
                    v-model="Form[item.fieldName].fieldValue"
                    maxlength="50"
                    @input="onInput()"
                  />
                </template>
                <template v-if="item.fieldType == 'textarea'">
                  <fks-input
                    v-model="Form[item.fieldName].fieldValue"
                    maxlength="50"
                    type="textarea"
                    :rows="3"
                    @input="onInput()"
                  />
                </template>
                <template v-if="item.fieldType == 'Date'">
                  <fks-date-picker
                    v-model="Form[item.fieldName].fieldValue"
                    type="date"
                    style="width: 100%"
                    placeholder="选择日期"
                    @input="onInput()"
                  />
                </template>
                <template v-if="item.fieldType == 'orgSelector'">
                  <fks-org-selector
                    url
                    :dept-id.sync="Form[item.fieldName].fieldValue.createDeptid"
                    :dept-name.sync="Form[item.fieldName].fieldValue.createDept"
                  />
                </template>
                <template v-if="item.fieldType == 'userSelector'">
                  <fks-user-selector
                    url
                    :username.sync="Form[item.fieldName].fieldValue.createBy"
                    :userfullname.sync="
                      Form[item.fieldName].fieldValue.createFullname
                    "
                  />
                </template>
              </fks-form-item>
            </div>
          </template>
        </fks-form>
      </div>

      <div v-show="form_setting_else">
        <h3>{{ LANG.CONTENT_SETTINGS_ELSE }}</h3>
        <fks-form>
          <template v-for="item in templateDetail">
            <fks-form-item
              v-if="
                item.fieldType == 'radio' &&
                  showInAttribute(item.fieldName, item.fieldType)
              "
              :key="item.fieldName"
              :span="12"
              :prop="item.fieldName"
              :label="item.alias"
            >
              <template v-if="item.fieldType == 'radio'">
                <fks-switch
                  v-model="Form[item.fieldName].fieldValue"
                  active-value="1"
                  inactive-value="0"
                  @change="onInput()"
                />
              </template>
            </fks-form-item>
          </template>
          <template v-if="field_AUTOPUBLISHFLAG != null">
            <fks-form-item
              :span="12"
              :label="field_AUTOPUBLISHFLAG.alias"
            >
              <fks-switch
                v-model="Form['AUTOPUBLISHFLAG'].fieldValue"
                active-value="1"
                inactive-value="0"
                @change="onInput()"
              />
            </fks-form-item>

            <fks-form-item
              v-if="Form['AUTOPUBLISHFLAG'].fieldValue == '1'"
              :span="24"
              :label="findFieldByName('PUBLISHDATE', templateDetail).alias"
            >
              <fks-date-picker
                v-model="Form['PUBLISHDATE'].fieldValue"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择日期"
                style="width: 100%"
                @input="onInput()"
              />
            </fks-form-item>
            <div
              v-if="Form['AUTOPUBLISHFLAG'].fieldValue == '1'"
              class="tip"
            >
              <div class="tip-content">
                <span style="font-size: 14px; line-height: 36px">{{
                  LANG.AUTOPUBLISH_TIP
                }}</span>
              </div>
            </div>
          </template>
        </fks-form>
      </div>

      <div v-if="field_FILE != null">
        <h3>{{ LANG.CONTENT_FILES }}</h3>
        <fks-form>
          <template>
            <fks-form-item :label="field_FILE.alias">
              <fks-upload
                :file-list="fileList"
                class="fks-upload"
                :action="upload_url"
                :with-credentials="true"
                :headers="{ 'Fawkes-Auth': accessToken }"
                :data="g9s1"
                :on-success="uploadFileSuccess"
                :on-error="uploadFileError"
                :on-remove="deleteFile"
                :on-download="handleDownLoad"
                :on-change="handleFileChange"
                :multiple="true"
                :limit="8"
              >
                <fks-button
                  size="small"
                  icon="fks-icon-upload-line"
                >
                  {{ LANG.UPLOAD }}
                </fks-button>
              </fks-upload>
            </fks-form-item>
          </template>
        </fks-form>
      </div>
    </div>

    <div
      v-if="!form_setting && !form_setting_else && field_FILE == null"
      style="
        display: flex;
        flex-direction: column;
        justify-content: center;
        height: 100%;
      "
    >
      <h2>{{ LANG.NO_SETTINGS }}</h2>
    </div>
  </div>
</template>

<script>
import { uuid } from '@/utils/util'
import { USER } from '@/store/State/stateTypes'
import { updateContentDetail, addContentDetail } from '../../api/index'
import { findFieldByName } from '@/modules/Content/api'
import { getFile, deleteFile, downloadFile } from '@/api/file'
import { download } from '@/utils/file'
import { detialInContent, detailNotShow } from '@/modules/Content/defaultData'
export default {
  name: 'AddDetail',
  props: {
    visible: {
      type: Boolean,
      default: true
    },
    operateType: {
      type: String,
      default: 'new'
    },
    currentContent: {
      type: Object
    },
    currentContentDetails: {
      type: Array
    },
    templateDetail: {
      type: Array
    }
  },
  data() {
    return {
      btnWidth: '',
      categoryId: '',
      templateId: '',
      label_position: 'left',
      loading: true,
      Visible: false,
      Form: {},
      content: {},
      contentDetail: [],
      g9s1: {},
      dept: {},
      fileToken: [],
      fileList: [], //全部文件
      fileListTemp: [],
      accessToken: this.$storage.get('access_token'),
      upload_url: this.VUE_APP_UPLOAD_API
    }
  },
  computed: {
    USER() {
      return this.$store.state[USER]
    },
    rules() {
      return {
        title: [{ required: true, trigger: ['blur'] }],
        createBy: [{ required: true, trigger: ['blur'] }]
      }
    },
    field_AUTOPUBLISHFLAG() {
      return findFieldByName('AUTOPUBLISHFLAG', this.templateDetail)
    },
    field_TITLE() {
      return findFieldByName('TITLE', this.templateDetail)
    },
    field_CONTEXT() {
      return findFieldByName('CONTEXT', this.templateDetail)
    },
    field_FILE() {
      return findFieldByName('FILE', this.templateDetail)
    },
    form_setting() {
      for (let i = 0; i < this.templateDetail.length; i++) {
        let item = this.templateDetail[i]
        if (
          item.fieldType != 'radio' &&
          this.showInAttribute(item.fieldName, item.fieldType)
        ) {
          return true
        }
      }

      return false
    },
    form_setting_else() {
      if (this.field_AUTOPUBLISHFLAG != null) return true
      for (let i = 0; i < this.templateDetail.length; i++) {
        let item = this.templateDetail[i]
        if (
          item.fieldType == 'radio' &&
          this.showInAttribute(item.fieldName, item.fieldType)
        ) {
          return true
        }
      }
      return false
    }
  },
  watch: {},
  mounted() {
    this.loading = true
    this.initData()
  },
  beforeDestroy() {
    this.resetData()
  },
  methods: {
    close() {
      // this.resetData()
      this.$emit('close')
    },
    onInput() {
      this.$forceUpdate()
    },
    contentChange(val) {
      this.Form.context = val
    },
    showInAttribute(name, type) {
      if (type == 'file') return false
      if (detialInContent.indexOf(type) > -1) return false
      if (detailNotShow.indexOf(name) > -1) return false
      return true
    },

    /**
     * @description: 提取Form表单中关于内容详情的部分，即（存储在数据库表content_detail中的内容）
     * @param {Object} form 填写的表单
     * @return {Object} DetailList 内容
     */
    formToDetailList(form) {
      let detailList = []
      for (let i = 0; i < this.templateDetail.length; i++) {
        let fieldName = this.templateDetail[i].fieldName
        let field = form[fieldName]
        if (
          Object.prototype.toString.call(field.fieldValue) === '[object Object]'
        ) {
          field.fieldValue = JSON.stringify(field.fieldValue)
        }
        field.contentId = this.currentContent.id
        detailList.push(field)
      }
      return detailList
    },

    /**
     * @description: 更新入口，完整性校验。由外部通过$ref调用
     *
     */
    update() {
      this.submitDetails()
    },

    submitDetails: async function () {
      let contentDetail = this.formToDetailList(
        JSON.parse(JSON.stringify(this.Form))
      )

      let oldContentDetail = []
      let newContentDetail = []

      contentDetail.forEach((item) => {
        if (item.isNew) {
          newContentDetail.push(item)
        } else {
          oldContentDetail.push(item)
        }
      })

      await this.updateContentDetail(oldContentDetail)
      await this.addContentDetail(newContentDetail)
      this.$emit('success')
    },

    updateContentDetail(contentDetail) {
      return updateContentDetail(contentDetail)
    },

    addContentDetail(contentDetail) {
      return addContentDetail(contentDetail)
    },

    /**
     * @description: 创建入口，完整性校验。由外部通过$ref调用
     *
     */
    create() {
      let contentDetail = this.formToDetailList(
        JSON.parse(JSON.stringify(this.Form))
      )

      this.addContentDetail(contentDetail)
        .then((res) => {
          if (res.status) {
            this.$emit('quit')
          }
        })
        .catch(() => {})
    },

    /**
     * @description: 附件相关处理
     */
    uploadFileSuccess(response, file, fileList) {
      let field = this.Form['FILE']
      if (response.status) {
        field.fieldValue = response.data.groupToken
        let fileT = {
          fileName: response.data.fileName,
          fileToken: response.data.fileToken
        }
        this.fileToken.push(fileT)
      } else {
        this.$message({
          type: 'error',
          message: response.message
        })
        this.fileList = this.fileList.filter((item) => {
          return item != file
        })
      }
    },
    handleFileChange(file, fileList) {
      // console.dir(file)
      // console.dir(fileList)
    },
    uploadFileError(file, fileList) {
      // console.dir(file)
      // console.dir(fileList)
    },
    deleteFile(file, fileList) {
      let temp = {
        f8s: [file.fileToken]
      }
      deleteFile(temp)
        .then((res) => {
          if (res.status) {
            this.$message({
              type: 'success',
              message: this.LANG.DELETE_SUCCESS
            })
          }
        })
        .catch(() => {})
    },
    handleDownLoad(file) {
      downloadFile(file.response ? file.response.fileToken : file.fileToken)
        .then((res) => {
          download(file, res.data)
        })
        .catch(() => {})
    },

    /**
     * @description: 根据可变字段名称filed.name获得该可变字段对象
     * @param {String} filed.name
     * @return {Object} filed
     */
    findFieldByName(name, list) {
      return findFieldByName(name, list)
    },

    /**
     * @description: 寻找filed.name为'file'的可变字段filed，
     *               filed.value为文件组的token
     *               将文件组的属性放入fileList用于页面展示
     */
    initFileList() {
      let field = this.Form['FILE']
      let fileGroupToken = field.fieldValue
      if (!fileGroupToken || fileGroupToken == '') {
        fileGroupToken = uuid(32, 16)
        this.g9s1 = { g9s: fileGroupToken }
        this.loading = false
        return
      }

      let g9s = [fileGroupToken]
      this.g9s1 = { g9s: fileGroupToken }

      getFile({ g9s: g9s })
        .then((res) => {
          if (res.status) {
            this.fileListTemp = res.data
            this.splitFileList()
          }
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    splitFileList() {
      let temp
      this.fileListTemp.forEach((e) => {
        temp = {
          name: e.fileName,
          url: e.link,
          ...e
        }
        this.fileList.push(temp)
      })
    },

    /**
     * @description: 根据contentId获得content，contentDetail，根据content.categoryId获取category的模板，根据模板渲染
     *
     */
    initData() {
      this.Form = JSON.parse(JSON.stringify(this.currentContent))
      for (let i = 0; i < this.templateDetail.length; i++) {
        let item = this.templateDetail[i]
        let temp = {
          fieldName: item.fieldName,
          fieldType: item.fieldType,
          isNew: true
        }
        this.Form[item.fieldName] = temp

        /**
         * @description: 表单渲染处理
         */
        if (
          temp.fieldType == 'orgSelector' ||
          temp.fieldType == 'userSelector'
        ) {
          this.Form[item.fieldName].fieldValue = {}
        }
        if (temp.fieldType == 'file') {
          // let newGroupToken = uuid(32, 16)
          // this.Form[item.fieldName].fieldValue = newGroupToken
          // this.g9s1 = { g9s: newGroupToken }
        }
      }

      for (let i = 0; i < this.currentContentDetails.length; i++) {
        let field = JSON.parse(JSON.stringify(this.currentContentDetails[i]))
        field.isNew = false

        this.Form[field.fieldName] = field
        /**
         * @description: 表单渲染处理
         */
        if (
          field.fieldType == 'orgSelector' ||
          field.fieldType == 'userSelector'
        ) {
          this.Form[field.fieldName].fieldValue = JSON.parse(
            this.Form[field.fieldName].fieldValue
          )
        }
        if (detialInContent.indexOf(field.fieldType) > -1) {
          this.Form[field.fieldName].fieldValue = this.Form[field.fieldType]
        }
      }
      if (this.Form['FILE']) {
        this.initFileList()
      } else {
        this.loading = false
      }
    },

    /**
     * @description: 清空数据
     */
    resetData() {
      this.Form = {}
      this.content = {}
      this.contentDetail = []
      this.statusHistory = []
      this.fileList = []
      this.fileToken = []
    }
  }
}
</script>

<style scoped lang="scss">
.add-content {
  width: 100%;
  overflow: scroll;

  h2 {
    text-align: center;
    color: #e9e9e9;
  }
}

.detail-container {
  padding-top: 16px;
  margin-right: 16px;
  margin-left: 32px;

  h3 {
    margin-top: 0;
    margin-bottom: 16px;
    color: #191919;
  }
}

.tip {
  width: 100%;
  height: 36px;
  padding-right: 8px;
  padding-left: 8px;
  margin-bottom: 16px;

  .tip-content {
    width: 100%;
    height: 36px;
    padding: 0 16px;
    border-left: 5px solid #50bfff;
    border-radius: 4px;
    color: #333;
    background-color: #ecf8ff;
  }
}
</style>
